package com.group.flagtivities;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

public class Create extends Activity implements OnClickListener {
	private static LinearLayout form;
	private static EditText room;
	private static EditText title;
	private static EditText description;
	private static EditText start;
	private static EditText end;
	private static ImageView type;
	private static ImageView permissionView;
	private static ProgressBar createIndicator;
	private static Button createButton;
	private static Button cancel;
	
	private static Bundle location;
	
	private static int permission = 0;
	private static int lat;
	private static int lon;
	private static int user_id;
	private static int type_id;
	
	private static long timeStart;
	private static long timeEnd;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create);
        
        findViews();
        configure();
        
        TextUtil.setFont((ViewGroup) findViewById(R.id.create), getAssets());
    }
	
	private void findViews() {
		createIndicator = (ProgressBar) findViewById(R.id.createIndicator);
        form = (LinearLayout) findViewById(R.id.form);
        description = (EditText) findViewById(R.id.description);
        room = (EditText) findViewById(R.id.room);
        start = (EditText) findViewById(R.id.start);
        end = (EditText) findViewById(R.id.end);
        title = (EditText) findViewById(R.id.title);
        type = (ImageView) findViewById(R.id.type);
        permissionView = (ImageView) findViewById(R.id.permission);
        createButton = (Button) findViewById(R.id.createButton);
        cancel = (Button) findViewById(R.id.cancel);
	}
	
	private void configure() {
		location = (Bundle) getIntent().getBundleExtra("Location");
        lat = location.getInt("Lat");
        lon = location.getInt("Lon");
        user_id = Flagtivities.user_id;
        type_id = 1;
        
        type.setOnClickListener(this);
        permissionView.setOnClickListener(this);
	}
	
	private void colorSwatch() {
		switch(type_id) {
		case TypePicker.ATHLETICS:
			type.setImageDrawable(getResources().getDrawable(R.drawable.background_type_red));
			break;
		case TypePicker.COMPUTER_SCIENCE:
			type.setImageDrawable(getResources().getDrawable(R.drawable.background_type_orange));
			break;
		case TypePicker.FINE_ARTS:
			type.setImageDrawable(getResources().getDrawable(R.drawable.background_type_yellow));
			break;
		case TypePicker.FOREIGN_LANGUAGE:
			type.setImageDrawable(getResources().getDrawable(R.drawable.background_type_green));
			break;
		case TypePicker.HUMANITIES:
			type.setImageDrawable(getResources().getDrawable(R.drawable.background_type_blue));
			break;
		case TypePicker.MATHEMATICS:
			type.setImageDrawable(getResources().getDrawable(R.drawable.background_type_indigo));
			break;
		case TypePicker.SOCIAL:
			type.setImageDrawable(getResources().getDrawable(R.drawable.background_type_violet));
			break;
		}
	}
	
	private void shake() {
		Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		form.startAnimation(shake);
	}
	
	private void setInteractability(boolean isInteractable) {
		title.setEnabled(isInteractable);
		room.setEnabled(isInteractable);
		start.setEnabled(isInteractable);
		end.setEnabled(isInteractable);
		description.setEnabled(isInteractable);
		createButton.setEnabled(isInteractable);
		cancel.setEnabled(isInteractable);
		permissionView.setClickable(isInteractable);
		type.setClickable(isInteractable);
		createIndicator.setVisibility(isInteractable ? View.GONE : View.VISIBLE);
	}
	
	private void create() {
		final String Description = description.getText().toString().trim();
		final String Room = room.getText().toString().trim();
		final String Title = title.getText().toString().trim();
		final String Start = start.getText().toString().trim();
		final String End = end.getText().toString().trim();
		
		description.setText(Description);
		room.setText(Room);
		title.setText(Title);
		start.setText(Start);
		end.setText(End);
					
		if (!Description.isEmpty() && !Room.isEmpty() && !Title.isEmpty() && !Start.isEmpty() && !End.isEmpty() && validateTimeStamps()) {
			setInteractability(false);
			createButton.setTextColor(Color.GRAY);
			Timer t = new Timer();
			t.schedule(new TimerTask() {
				public void run() {
					WebUtil.createActivity(permission, type_id, user_id, Description, lat, lon, Room, Title, ""+timeStart, ""+timeEnd);
					finish();
				}
			}, 3000);
		}else {
			if (Title.isEmpty()) {
				title.requestFocus();
			}else if (Room.isEmpty()) {
				room.requestFocus();
			}else if (start.getText().toString().isEmpty()) {
				start.requestFocus();
			}else if (end.getText().toString().isEmpty()) {
				end.requestFocus();
			}else if (Description.isEmpty()) {
				description.requestFocus();
			}
			shake();
		}
	}
	
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.permission:
			permission = (permission == 0) ? 1 : 0;
			if (permission == 0) ((ImageView) view).setImageDrawable(getResources().getDrawable(R.drawable.public_black));
			else if (permission == 1) ((ImageView) view).setImageDrawable(getResources().getDrawable(R.drawable.private_black));
			break;
		case R.id.type:
			startActivityForResult(new Intent(this, TypePicker.class), TypePicker.REQUEST_CODE);
			break;
		case R.id.cancel:
			finish();
			break;
		case R.id.createButton:
			create();
			break;
		}
	}
	
	private boolean validateTimeStamps() {
		final String Start = start.getText().toString().trim();
		final String End = end.getText().toString().trim();
		
		Pattern pattern = Pattern.compile("[01][0-9]/[0-3][0-9]/[0-9][0-9][0-9][0-9] @ [0-2][0-9]:[0-5][0-9]");
		
		Matcher matcher = pattern.matcher(Start);
		boolean isValidStart = matcher.matches();
		matcher = pattern.matcher(End);
		boolean isValidEnd = matcher.matches();
		
		if (!isValidStart) {
			start.setText("");
			start.requestFocus();
		}
		
		if (!isValidEnd) {
			end.setText("");
			end.requestFocus();
		}
		
		if (!isValidStart || !isValidEnd) {
			return false;
		}
		
		int monthStart = Integer.parseInt(Start.substring(0, 2));
		int monthEnd = Integer.parseInt(End.substring(0, 2));
		int dayStart = Integer.parseInt(Start.substring(3, 5));
		int dayEnd = Integer.parseInt(End.substring(3, 5));
		int yearStart = Integer.parseInt(Start.substring(6, 10));
		int yearEnd = Integer.parseInt(End.substring(6, 10));
		int hourStart = Integer.parseInt(Start.substring(13, 15));
		int hourEnd = Integer.parseInt(End.substring(13, 15));
		int minStart = Integer.parseInt(Start.substring(16));
		int minEnd = Integer.parseInt(End.substring(16));
		
		boolean isValidStartDate = validateDate(monthStart, dayStart, yearStart);
		boolean isValidEndDate = validateDate(monthEnd, dayEnd, yearEnd);
		
		if (!isValidStartDate || hourStart >= 24) {
			start.setText("");
			start.requestFocus();
		}
		
		if (!isValidEndDate || hourEnd >= 24) {
			end.setText("");
			end.requestFocus();
		}
		
		if (!isValidStartDate || !isValidEndDate || hourStart >= 24 || hourEnd >= 24) {
			return false;
		}
		
		long longStart = convertToUNIX(monthStart, dayStart, yearStart, hourStart, minStart);
		long longEnd = convertToUNIX(monthEnd, dayEnd, yearEnd, hourEnd, minEnd);
		
		if (longStart >= longEnd) {
			end.setText("");
			end.requestFocus();
			return false;
		}
		
		Calendar calendar = Calendar.getInstance();
		
		if (calendar.getTimeInMillis() / 1000 >= longEnd) {
			end.setText("");
			end.requestFocus();
			return false;
		}
		
		timeStart = longStart;
		timeEnd = longEnd;
				
		return true;
	}

	private long convertToUNIX(int month, int day, int year, int hour, int min) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, day);
		calendar.set(Calendar.MONTH, (month - 1));
		calendar.set(Calendar.YEAR, year);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MINUTE, min);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		
		return calendar.getTimeInMillis() / 1000;
	}
	
	private boolean validateDate(int month, int day, int year) {
		if (year < 2012) return false;
		if (month > 12) return false;
		if (day < 1 || day > 31) return false;
		switch (month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			return day <= 31;
		case 2:
			if (isLeapYear(year)) return day <= 29;
			else return day <= 28;
		case 4:
		case 6:
		case 9:
		case 11:
			return day <= 30;
		}
		
		return false;
	}
	
	private boolean isLeapYear(int year) {
		if (year % 4 == 0 && year % 100 != 0) {
			return true;
		}else if (year % 4 == 0 && year % 100 == 0 && year % 400 == 0) {
			return true;
		}else {
			return false;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TypePicker.REQUEST_CODE:
			if (resultCode != TypePicker.RESULT_CANCELED) {
				type_id = resultCode;
				colorSwatch();
			}
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
	
}
